//package com.zzyl.oss.config;
//
//import com.aliyun.oss.OSS;
//import com.aliyun.oss.OSSClientBuilder;
//import com.aliyun.oss.model.CannedAccessControlList;
//import com.aliyun.oss.model.CreateBucketRequest;
//import com.aliyun.oss.model.SetBucketLoggingRequest;
//import com.zzyl.oss.properties.AliOssConfigProperties;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//@Slf4j
//@Configuration
//public class OssAliyunAutoConfig {
//
//    @Autowired
//    AliOssConfigProperties aliOssConfigProperties;
//
//    @Bean
//    public OSS ossClient(){
//        log.info("-----------------开始创建OSSClient--------------------");
//        OSS ossClient = new OSSClientBuilder().build(aliOssConfigProperties.getEndpoint(),
//                aliOssConfigProperties.getAccessKeyId(), aliOssConfigProperties.getAccessKeySecret());
//        //判断容器是否存在,不存在就创建
//        if (!ossClient.doesBucketExist(aliOssConfigProperties.getBucketName())) {
//            ossClient.createBucket(aliOssConfigProperties.getBucketName());
//            CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliOssConfigProperties.getBucketName());
//            //设置问公共可读
//            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
//            ossClient.createBucket(createBucketRequest);
//        }
//
//        //添加客户端访问日志
//        SetBucketLoggingRequest request = new SetBucketLoggingRequest(aliOssConfigProperties.getBucketName());
//        // 设置存放日志文件的存储空间。
//        request.setTargetBucket(aliOssConfigProperties.getBucketName());
//        // 设置日志文件存放的目录。
//        request.setTargetPrefix(aliOssConfigProperties.getBucketName());
//        ossClient.setBucketLogging(request);
//
//        log.info("-----------------结束创建OSSClient--------------------");
//        return ossClient;
//    }
//
//
//}
package com.zzyl.oss.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.SetBucketLoggingRequest;
import com.zzyl.oss.properties.AliOssConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class OssAliyunAutoConfig {

    @Autowired
    AliOssConfigProperties aliOssConfigProperties;

    @Bean
    @ConditionalOnProperty(name = "oss.enabled", havingValue = "true", matchIfMissing = false)
    public OSS ossClient() {
        log.info("-----------------开始创建OSSClient--------------------");
        log.info("OSS配置 - Endpoint: {}, Bucket: {}",
                aliOssConfigProperties.getEndpoint(),
                aliOssConfigProperties.getBucketName());

        try {
            // 1. 先创建基础OSS客户端
            OSS ossClient = new OSSClientBuilder().build(
                    aliOssConfigProperties.getEndpoint(),
                    aliOssConfigProperties.getAccessKeyId(),
                    aliOssConfigProperties.getAccessKeySecret());

            // 2. 延迟初始化bucket相关操作，避免启动失败
            initializeBucket(ossClient);

            log.info("-----------------OSSClient创建成功--------------------");
            return ossClient;

        } catch (OSSException e) {
            log.error("-----------------OSSClient创建失败: {}--------------------", e.getMessage());
            log.error("错误代码: {}, 请求ID: {}", e.getErrorCode(), e.getRequestId());
            throw new RuntimeException("OSS客户端初始化失败，请检查AccessKey配置: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("-----------------OSSClient创建异常: {}--------------------", e.getMessage());
            throw new RuntimeException("OSS客户端初始化异常: " + e.getMessage(), e);
        }
    }

    /**
     * 延迟初始化bucket，避免因权限问题导致应用无法启动
     */
    private void initializeBucket(OSS ossClient) {
        try {
            String bucketName = aliOssConfigProperties.getBucketName();

            // 判断容器是否存在,不存在就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                log.info("Bucket不存在，开始创建: {}", bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                // 设置为公共可读
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
                log.info("Bucket创建成功: {}", bucketName);
            } else {
                log.info("Bucket已存在: {}", bucketName);
            }

            // 添加客户端访问日志（可选操作，可注释掉）
            try {
                SetBucketLoggingRequest request = new SetBucketLoggingRequest(bucketName);
                request.setTargetBucket(bucketName);
                request.setTargetPrefix(bucketName);
                ossClient.setBucketLogging(request);
                log.info("Bucket日志配置完成");
            } catch (Exception e) {
                log.warn("设置Bucket日志失败，但不影响主要功能: {}", e.getMessage());
            }

        } catch (OSSException e) {
            log.warn("Bucket初始化操作失败，但OSS客户端仍可创建: {}", e.getMessage());
            log.warn("可能的原因: 权限不足或Bucket操作受限");
            // 这里不抛出异常，让OSS客户端继续使用
        } catch (Exception e) {
            log.warn("Bucket初始化出现异常: {}", e.getMessage());
            // 同样不抛出异常，保证应用能正常启动
        }
    }
}